package com.example.demoex3.services;

import com.example.demoex3.model.*;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class DataService implements InitializingBean {
    public static String CORONA_VIRUS_DATA_URL ="https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    private final List<Model> allRegionStats= new ArrayList<>();
    public List<Model> getAllRegionStats() {
        return allRegionStats;
    }

    //定时任务每天凌晨1点刷新
    @Scheduled(cron="${nie.Schedules.updateVirusDataCron}")
    public void fetchConavirusData() throws IOException {
        //爬取全球新冠病毒数据
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent","FF"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        //获取csv文件信息
        Reader reader = new InputStreamReader(body.getInputStream());
        CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
        for(CSVRecord record:parser) {
            Model model = new Model();
            model.setState(record.get("Province/State"));
            model.setCountry(record.get("Country/Region"));
            model.setLatestTotalCases(Integer.parseInt(record.get(record.size() - 1)));
            model.setDiffFromPrevDay(Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2)));
            allRegionStats.add(model);
        }

    }

    //确保能够拉一次数据
    @Override
    public void afterPropertiesSet() throws Exception{
        fetchConavirusData();
    }

}
